package tree.tree2.symmetry.Ancestor;

import tree.TreeNode;

/**
 * @ClassName LowestCommonAncestor
 * @Description TODO
 * @Author lenovo
 * @Date 2023-05-08 10:39
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class LowestCommonAncestor {

    /**
     * 236. 二叉树的最近公共祖先
     * 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
     * <p>
     * 百度百科中最近公共祖先的定义为：“对于有根树 T 的两个节点 p、q，最近公共祖先表示为一个节点 x，满足 x 是 p、q 的祖先且 x 的深度尽可能大（一个节点也可以是它自己的祖先）。”
     * <p>
     * <p>
     * <p>
     * 示例 1：
     * <p>
     * <p>
     * 输入：root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
     * 输出：3
     * 解释：节点 5 和节点 1 的最近公共祖先是节点 3 。
     *     3
     *  1    5
     * 1,5 -> 3
     * 3,5 -> 3
     * <p>
     *        2
     *   3         6
     * 1   5
     */

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) return root;
        int a = root.val;
        TreeNode left = lowestCommonAncestor(root.left,p,q);
        TreeNode right = lowestCommonAncestor(root.right,p,q);

        if(left != null && right ==null){
            return left;
        }
        if(left == null && right !=null){
            return right;
        }
        if(left != null && right !=null){
            return root;
        }
        return null;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(2);
        root.left = new TreeNode(3);
        root.left.right = new TreeNode(5);
        root.right = new TreeNode(6);

        LowestCommonAncestor lowestCommonAncestor = new LowestCommonAncestor();
        System.out.println(lowestCommonAncestor.lowestCommonAncestor(root, root.left.right, root.right));
//        TreeNode rootTreeNode = new TreeNode(3);
//        rootTreeNode.left = new TreeNode(1);
//        rootTreeNode.right = new TreeNode(5);

//        lowestCommonAncestor.lowestCommonAncestor(rootTreeNode, rootTreeNode.right, rootTreeNode);
    }
}